"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Compatibility
Case Name   : 验证escaped by 'char'转义字符\的同义替换取值,部分测试点合理报错
Create At   : 2023/06/02
Owner       : n@ningyali
Description :
        1.创建表
        2.导入数据，指定参数fields escaped的值为 #
        3.导入数据，指定参数fields escaped的值为 9
        4.导入数据，指定参数fields escaped的值为 9/3
        5.导入数据，指定参数fields escaped的值为 false
Expect      :
        1.成功
        2.成功
        3.成功
        4.合理报错
        5.合理报错
History     :
"""
import os
import unittest

from yat.test import Node

from testcase.COMPATIBILITY.GRAMMAR.LOAD. \
    Opengauss_Compatibility_Grammar_Load_Common import LoadData
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class LoadData0051(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.load_data = LoadData()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.case_lable = 'load_data_0051'
        self.db_name = f'db_{self.case_lable}'
        self.t_name = f't_{self.case_lable}'
        self.file_path = os.path.join('/home', self.pri_user.ssh_user)
        self.cols = 'c1 text'

        text1 = '-----创建数据文件；expect:创建成功-----'
        self.log.info(text1)
        self.data1 = r"今天天气好晴朗#r处处好风光\"#r\"回车"
        self.data2 = "今天天9r9n气好晴朗9r9n处处好风光"
        self.data3 = "今天天9/3r9/3n气好晴朗9/3r9/3n处处好风光"
        self.data4 = "今天天falserfalsen气好晴朗falserfalsen处处好风光"
        res = self.load_data.create_data_file(self.pri_user, self.case_lable,
                                              self.data1, self.data2,
                                              self.data3, self.data4)
        self.assertTrue(res, '执行失败:' + text1)

        text2 = '-----创建兼容B库；expect:创建成功-----'
        self.log.info(text2)
        res = self.load_data.create_b_db(self.pri_sh, self.db_name)
        self.assertTrue(res, '执行失败:' + text2)

    def test_load(self):
        text = '--------step1：创建表；expect：建表成功--------'
        self.log.info(text)
        res = self.load_data.create_table(self.pri_sh, self.db_name,
                                          self.t_name, self.cols)
        self.assertTrue(res, '执行失败:' + text)

        text = '------step2：导入数据，指定参数fields escaped的值为#；' \
               'expect：成功------'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_1.txt')
        sql = f'''load data infile '{f_path}' into table {self.t_name}
            fields escaped by '#' enclosed by '\\"';
            select * from {self.t_name};'''
        res1 = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        self.log.info(res1)
        rows, _ = self.common.parse_sql_query_res(res1)
        expect = [['今天天气好晴朗\\r处处好风光"\\r"回车']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = '------step3：导入数据，指定参数fields escaped的值为9；' \
               'expect：成功------'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_2.txt')
        sql = f'''truncate table {self.t_name};
            load data infile '{f_path}' into table {self.t_name}
            fields escaped by '9';
            select * from {self.t_name};'''
        res2 = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        self.log.info(res2)
        rows, _ = self.common.parse_sql_query_res(res2)
        expect = [['今天天\\r    +'], ['气好晴朗\\r +'], ['处处好风光']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = '------step4：导入数据，指定参数fields escaped的值为9/3；' \
               'expect：合理报错------'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_3.txt')
        res3 = self.load_data.load_data(self.pri_sh, self.db_name,
                                        self.t_name, f_path, into_type='',
                                        escaped_by='9/3', col_end='\\"')
        msg = 'ERROR:  COPY escape must be a single one-byte character'
        self.assertIn(msg, res3, '执行失败' + text)

        text = '------step7：导入数据，指定参数fields escaped的值为false；' \
               'expect：合理报错------'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_4.txt')
        res4 = self.load_data.load_data(self.pri_sh, self.db_name,
                                        self.t_name, f_path, into_type='',
                                        escaped_by='false', col_end='\\"')
        rows, _ = self.common.parse_sql_query_res(res4)
        msg = 'ERROR:  COPY escape must be a single one-byte character'
        self.assertIn(msg, res4, '执行失败' + text)

    def tearDown(self):
        self.log.info('-----清理环境-----')
        res = self.load_data.clear_env(self.pri_sh, self.pri_user,
                                       self.db_name,
                                       os.path.join(self.file_path,
                                                    f"{self.case_lable}*"))
        self.assertTrue(res, '执行失败:清理环境')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
